﻿using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace IOA.MES.TcpApi
{

    /// <summary>
    /// 全局过滤器
    /// </summary>
    public class CommonFilter : ActionFilterAttribute, IActionFilter
    {
        private Logger logger = LogManager.GetLogger(nameof(CommonFilter));
        private Stopwatch watcher;
        private object lockObj = new object();
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            watcher = new Stopwatch();
            watcher.Start();

            base.OnActionExecuting(actionContext);
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            watcher.Stop();
            try
            {
                var request = HttpContext.Current.Request;
                HttpContext.Current.Request.InputStream.Position = 0;
                var length = HttpContext.Current.Request.InputStream.Length;
                var buffer = new byte[length];
                HttpContext.Current.Request.InputStream.Read(buffer, 0, (int)length);

                var dictLog = new Dictionary<string, object>();
                dictLog.Add("Url", request.Url.AbsolutePath.ToString());
                dictLog.Add("Elapsed", watcher.ElapsedMilliseconds);
                dictLog.Add("Body", Encoding.UTF8.GetString(buffer));

                if (actionExecutedContext.Exception == null)
                {
                    var response = actionExecutedContext.Response.Content.ReadAsStringAsync().Result;
                    dictLog.Add("Response", response);
                    logger.Info(JsonConvert.SerializeObject(dictLog));
                }
                else
                {
                    var response = new ResultJson<object>(500, "服务器忙");
                    if (actionExecutedContext.Exception is BizException)
                    {
                        var bizException = actionExecutedContext.Exception as BizException;
                        dictLog.Add("ErrCode", bizException.ErrCode);
                        response = new ResultJson<object>(bizException.ErrCode, bizException.Message);
                    }
                    dictLog.Add("ErrMsg", response.ErrMsg);
                    dictLog.Add("Response", response);
                    actionExecutedContext.Response = new HttpResponseMessage
                    {
                        StatusCode = System.Net.HttpStatusCode.OK,
                        Content = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json")
                    };

                    if (response.ErrCode == 500)
                    {
                        logger.Fatal(actionExecutedContext.Exception, JsonConvert.SerializeObject(dictLog));
                    }
                    else
                    {
                        logger.Warn(JsonConvert.SerializeObject(dictLog));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, $"OnActionExecuted出错：{ex.Message}");
            }

            base.OnActionExecuted(actionExecutedContext);
        }
    }
}
